"""
证书刷新 API
用于刷新 DNS 验证记录
"""
from fastapi import APIRouter, Depends, Request
from motor.motor_asyncio import AsyncIOMotorDatabase
from pydantic import BaseModel, Field
from bson import ObjectId
from typing import List

from database.connection import get_database
from api.deps_v1 import get_current_user
from utils.response import success, error
from models.response import ErrorCode

router = APIRouter(prefix="/sac/v1/certificates", tags=["证书服务"])

# 服务名称
SERVICE_NAME = "certificates"


# ========== 请求模型 ==========

class RefreshDNSRecordsRequest(BaseModel):
    """刷新 DNS 验证记录请求"""
    certificate_id: str = Field(..., description="证书 ID")


class RefreshDNSRecordsResult(BaseModel):
    """刷新 DNS 验证记录结果"""
    certificate_id: str
    dns_validation_records: List[dict]
    message: str


# ========== API 接口 ==========

@router.post("/RefreshDNSRecords", summary="刷新 DNS 验证记录")
async def refresh_dns_records(
    request: Request,
    body: RefreshDNSRecordsRequest,
    current_user: dict = Depends(get_current_user),
    db: AsyncIOMotorDatabase = Depends(get_database)
):
    """
    刷新 DNS 验证记录
    
    用于重新获取 DNS TXT 记录的值
    """
    try:
        request_id = request.state.request_id
        
        if not ObjectId.is_valid(body.certificate_id):
            return error(
                request, "RefreshDNSRecords", SERVICE_NAME,
                ErrorCode.INVALID_PARAMETER,
                detail="无效的证书 ID"
            )
        
        # 查询证书
        cert = await db.certificates.find_one({
            "_id": ObjectId(body.certificate_id),
            "user_id": current_user["id"],
            "deleted_at": None
        })
        
        if not cert:
            return error(
                request, "RefreshDNSRecords", SERVICE_NAME,
                ErrorCode.CERT_NOT_FOUND
            )
        
        # 重新获取 DNS 验证记录
        from services.certificate_service import CertificateService
        
        domains = [cert["domain"]] + cert.get("sans", [])
        dns_records = await CertificateService.get_dns_validation_info(
            domains=domains,
            ca_provider=cert["ca_provider"],
            contact_email=current_user.get("email", "")
        )
        
        # 更新数据库
        await db.certificates.update_one(
            {"_id": ObjectId(body.certificate_id)},
            {"$set": {"dns_validation_records": dns_records}}
        )
        
        return success(
            request, "RefreshDNSRecords", SERVICE_NAME,
            RefreshDNSRecordsResult(
                certificate_id=body.certificate_id,
                dns_validation_records=dns_records,
                message="DNS 验证记录已刷新"
            ).model_dump()
        )
        
    except Exception as e:
        return error(
            request, "RefreshDNSRecords", SERVICE_NAME,
            ErrorCode.SYSTEM_ERROR,
            detail=str(e)
        )

